﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using DataAccessObject;
using EntityObject;
using Facebook;
using FacebookApp.SharedLibraries;
using ThangNM_LIB.EO;
using ThangNM_LIB.FUNC;

namespace FacebookApp
{
    public partial class Register_Request : System.Web.UI.Page
    {
        public RequestEO objRequestEO
        {
            get { return (RequestEO)ViewState["objRequestEO"]; }
            set { ViewState["objRequestEO"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlType.DataSource = ConstEx.Facebook_Type.Get_Facebook_Type();
                ddlType.DataTextField = "Value";
                ddlType.DataValueField = "Key";
                ddlType.DataBind();
                pnlCheck.Visible = true;
            }
        }

        protected void btnCheck_Click(object sender, EventArgs e)
        {
            try
            {
                //ScheduleJobs.btnCheck_Click(ddlType.SelectedValue, txtsEmail.Text, txtsUrl.Text);
                //return;


                MsgUC1.setClearMsg();
                Facebook.FacebookClient FBClient = new FacebookClient();
                FBClient.AppId = OtherEx.getAppSettings("Facebook_AppId");
                FBClient.AppSecret = OtherEx.getAppSettings("Facebook_AppSecret");
                FBClient.AccessToken = "CAAXaKZCf3qnkBAB0GyTyozEBwHq2DEEhokYxZCNmlRq05FynZAzVwBFvvGES68TuTnJ2IO32XQuC46BZC1clN7bId4CsBEDgnnmYzM6JBq60njv7uAA0dNLCbwbbLpfch0qIlzzHuuurDZBabmoCDcFsK8bv6Dx7diTVWu9JxQvvWvwhBkeMp";
                ScheduleJobs.Facebook_Object ctl = new ScheduleJobs.Facebook_Object();
                FacebookOptionEO objFBO = new FacebookOptionEO(ConstEx.Facebook_Type.unknown);
                MatchCollection mclTemp;
                objRequestEO = new RequestEO();
                objRequestEO.sFID = StringEx.Trim(txtsUrl.Text).ToLower();
                if (CommonsCheck.IsValidEmail(txtsEmail.Text))
                    objRequestEO.sEmail = StringEx.Trim(txtsEmail.Text);
                else
                {
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Email không đúng định dạng");
                    return;
                }
                if (String.IsNullOrEmpty(objRequestEO.sFID))
                {
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Bạn phải nhập Url hoặc ID Facebook");
                    return;
                }
                else if (StringEx.IsNumeric(objRequestEO.sFID, TypeCode.Int64))
                {
                    objFBO.type = Convert.ToInt16(ddlType.SelectedValue);
                    if (objFBO.type > 40)
                        objFBO.id_status_photo_video_link_event_offer_note = objRequestEO.sFID;
                    else
                        objFBO.id_user_page_group = objRequestEO.sFID;
                }
                else if (CommonsCheck.isUrl(objRequestEO.sFID))
                {
                    String sUrl_Temp = StringEx.Remove_Protocol_From_Url(objRequestEO.sFID);
                    if (objRequestEO.sFID.Contains("/profile.php?") || objRequestEO.sFID.Contains("app_scoped_user_id/"))  //https://www.facebook.com/profile.php?id=100001796888543
                    {
                        objFBO.id_user_page_group = StringEx.Get_Query_String_From_Url(objRequestEO.sFID, "id");

                        objFBO.type = ConstEx.Facebook_Type.user;
                        //MsgUC1.setNotifications(ConstEx.FunctionSetMsg.INFO, "user - " + objFBO.id_user_page_group);
                        //return;
                    }
                    else if (objRequestEO.sFID.Contains("/pages/"))  //https://www.facebook.com/pages/Da-Lao-L%C3%A2m-%C3%90%E1%BB%93ng-Vietnam/113664941980705
                    {
                        objFBO.id_user_page_group = StringEx.Split_sFB_ID(sUrl_Temp, 3, '/');

                        objFBO.type = ConstEx.Facebook_Type.page;
                        //MsgUC1.setNotifications(ConstEx.FunctionSetMsg.INFO, "page - " + objFBO.id_user_page_group);
                        //return;
                    }
                    else if (objRequestEO.sFID.Contains("/groups/"))  //https://www.facebook.com/groups/hanoi.don.nha.cho.do.chat/?ref=br_rs
                    {
                        objFBO.id_user_page_group = StringEx.Split_sFB_ID(sUrl_Temp, 2, '/');

                        objFBO.type = ConstEx.Facebook_Type.group;
                        //MsgUC1.setNotifications(ConstEx.FunctionSetMsg.INFO, "group - " + objFBO.id_user_page_group);
                        //return;
                    }

                    else if (objRequestEO.sFID.Contains("/posts/"))  //https://www.facebook.com/share2everyone/posts/784604151666842
                    {
                        //mclTemp = Regex.Matches(sUrl, "(?<=facebook.com/).*?(?=/posts/)", RegexOptions.Singleline);
                        //objFBO.id_user_page_group = StringEx.TrimEx((mclTemp.Count > 0 ? mclTemp[0].Groups[0].Value : null));
                        objFBO.id_user_page_group = StringEx.Split_sFB_ID(sUrl_Temp, 1, '/');

                        //mclTemp = Regex.Matches(sUrl, "(?<=/posts/)(\\d+)", RegexOptions.Singleline);
                        //objFBO.id_status_photo_video_link_event_offer_note = StringEx.TrimEx((mclTemp.Count > 0 ? mclTemp[0].Groups[0].Value : null));
                        objFBO.id_status_photo_video_link_event_offer_note = StringEx.Split_sFB_ID(sUrl_Temp, 3, '/');

                        objFBO.type = ConstEx.Facebook_Type.feed;
                        //MsgUC1.setNotifications(ConstEx.FunctionSetMsg.INFO, "posts - " + objFBO.id_user_page_group + "_" + objFBO.id_status_photo_video_link_event_offer_note);
                        //return;
                    }
                    else if (objRequestEO.sFID.Contains("/photos/"))  //https://www.facebook.com/share2everyone/photos/a.263007110493218.60859.262997240494205/773056179488306/?type=3&theater
                    {
                        //mclTemp = Regex.Matches(sUrl, "(?<=facebook.com/).*?(?=/photos/)", RegexOptions.Singleline);
                        //objFBO.id_user_page_group = StringEx.TrimEx((mclTemp.Count > 0 ? mclTemp[0].Groups[0].Value : null));
                        objFBO.id_user_page_group = StringEx.Split_sFB_ID(sUrl_Temp, 1, '/');

                        //mclTemp = Regex.Matches(sUrl, "(/\\d+)(?=/?type=3)", RegexOptions.Singleline);
                        //objFBO.id_status_photo_video_link_event_offer_note = StringEx.TrimEx((mclTemp.Count > 0 ? mclTemp[0].Groups[0].Value : null));
                        objFBO.id_status_photo_video_link_event_offer_note = StringEx.Split_sFB_ID(sUrl_Temp, 4, '/');

                        objFBO.type = ConstEx.Facebook_Type.photo;
                        //MsgUC1.setNotifications(ConstEx.FunctionSetMsg.INFO, "photo - " + objFBO.id_user_page_group + "_" + objFBO.id_status_photo_video_link_event_offer_note);
                        //return;
                    }
                    else if (objRequestEO.sFID.Contains("/photo.php?"))  //https://www.facebook.com/photo.php?fbid=814552615357737&set=a.115479441931728.30190.100004090194045&type=3&theater
                    {
                        mclTemp = Regex.Matches(objRequestEO.sFID, "(\\d+)(?=&type)", RegexOptions.Singleline);
                        objFBO.id_user_page_group = StringEx.TrimEx((mclTemp.Count > 0 ? mclTemp[0].Groups[0].Value : null));

                        mclTemp = Regex.Matches(objRequestEO.sFID, "(?<=a.)(\\d+)", RegexOptions.Singleline);
                        objFBO.id_status_photo_video_link_event_offer_note = StringEx.TrimEx((mclTemp.Count > 0 ? mclTemp[0].Groups[0].Value : null));

                        //objFBO.id_user_page_group = StringEx.Split_sFB_ID(sUrl_Temp, 1, '/');//100004090194045
                        //objFBO.id_status_photo_video_link_event_offer_note = StringEx.Split_sFB_ID(sUrl_Temp, 4, '/');//115479441931728

                        objFBO.type = ConstEx.Facebook_Type.photo;
                        //MsgUC1.setNotifications(ConstEx.FunctionSetMsg.INFO, "photo - " + objFBO.id_user_page_group + "_" + objFBO.id_status_photo_video_link_event_offer_note);
                        //return;
                    }
                    else if (objRequestEO.sFID.Contains("/videos/"))  //https://www.facebook.com/OfficeSurvivalGuide/videos/1557368117924354/
                    {
                        //mclTemp = Regex.Matches(sUrl, "(?<=facebook.com/).*?(?=/videos/)", RegexOptions.Singleline);
                        //objFBO.id_user_page_group = StringEx.TrimEx((mclTemp.Count > 0 ? mclTemp[0].Groups[0].Value : null));
                        objFBO.id_user_page_group = StringEx.Split_sFB_ID(sUrl_Temp, 1, '/');

                        //mclTemp = Regex.Matches(sUrl, "(?<=/videos/)(\\d+)", RegexOptions.Singleline);
                        //objFBO.id_status_photo_video_link_event_offer_note = StringEx.TrimEx((mclTemp.Count > 0 ? mclTemp[0].Groups[0].Value : null));
                        objFBO.id_status_photo_video_link_event_offer_note = StringEx.Split_sFB_ID(sUrl_Temp, 3, '/');

                        objFBO.type = ConstEx.Facebook_Type.video;
                        //MsgUC1.setNotifications(ConstEx.FunctionSetMsg.INFO, "video - " + objFBO.id_user_page_group + "_" + objFBO.id_status_photo_video_link_event_offer_note);
                        //return;
                    }
                    else if (objRequestEO.sFID.Contains("/permalink/"))  //https://www.facebook.com/groups/1419395631696098/permalink/1539210119714648/
                    {
                        objFBO.id_user_page_group = StringEx.Split_sFB_ID(sUrl_Temp, 2, '/');//100004090194045
                        objFBO.id_status_photo_video_link_event_offer_note = StringEx.Split_sFB_ID(sUrl_Temp, 4, '/');//115479441931728

                        objFBO.type = ConstEx.Facebook_Type.feed;
                        //MsgUC1.setNotifications(ConstEx.FunctionSetMsg.INFO, "permalink - " + objFBO.id_user_page_group + "_" + objFBO.id_status_photo_video_link_event_offer_note);
                        //return;
                    }
                    else if (objRequestEO.sFID.Contains("/permalink.php?"))  //https://www.facebook.com/permalink.php?story_fbid=852816991454856&id=100001796888543
                    {
                        objFBO.id_user_page_group = StringEx.Get_Query_String_From_Url(objRequestEO.sFID, "id");
                        objFBO.id_status_photo_video_link_event_offer_note = StringEx.Get_Query_String_From_Url(objRequestEO.sFID, "story_fbid");

                        objFBO.type = ConstEx.Facebook_Type.feed;
                        //MsgUC1.setNotifications(ConstEx.FunctionSetMsg.INFO, "permalink - " + objFBO.id_user_page_group + "_" + objFBO.id_status_photo_video_link_event_offer_note);
                        //return;
                    }
                    else
                    {
                        objFBO.id_user_page_group = StringEx.Split_sFB_ID(sUrl_Temp, 1, '/');
                        objFBO.type = Convert.ToInt16(ddlType.SelectedValue);
                        //MsgUC1.setNotifications(ConstEx.FunctionSetMsg.INFO, "user/page/group - " + objFBO.id_user_page_group);
                        //return;
                    }
                }

                switch (objFBO.type)
                {
                    case ConstEx.Facebook_Type.user:
                    case ConstEx.Facebook_Type.page:
                    case ConstEx.Facebook_Type.group:
                        objFBO = ctl.User_Page_Group(FBClient, objFBO);
                        break;
                    case ConstEx.Facebook_Type.feed:
                        MsgUC1.setNotifications(ConstEx.FunctionSetMsg.INFO, "123.");
                        objFBO.type = ConstEx.Facebook_Type.unknown;
                        objFBO = ctl.Post_Photo_Video_Link_Event_Offer_Note(FBClient, objFBO);
                        break;
                    case ConstEx.Facebook_Type.status:
                    case ConstEx.Facebook_Type.photo:
                    case ConstEx.Facebook_Type.video:
                    case ConstEx.Facebook_Type.link:
                    case ConstEx.Facebook_Type.events:
                    case ConstEx.Facebook_Type.offer:
                    case ConstEx.Facebook_Type.note:
                        objFBO = ctl.Post_Photo_Video_Link_Event_Offer_Note(FBClient, objFBO);
                        break;
                    default:
                        break;
                }
                if (objFBO == null || String.IsNullOrEmpty(objFBO.name))
                {
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.INFO, "Không xác định được loại đối tượng Facebook bạn nhập vào.");
                    return;
                }
                else
                {
                    lblID.Text = objFBO.id_status_photo_video_link_event_offer_note;
                    lblType.Text = GetListConstantsEx.FindValue_ByKey(ConstEx.Facebook_Type.Get_Facebook_Type_Full(), objFBO.type);
                    lblOther.Text = objFBO.name;
                    objRequestEO.iType = objFBO.type;
                    objRequestEO.iStatus = FacebookApp.SharedLibraries.Constants.Request_iStatus.received;
                    if (objFBO.type > 40)
                        objRequestEO.sFID = objFBO.id_user_page_group + "_" + objFBO.id_status_photo_video_link_event_offer_note;
                    else
                        objRequestEO.sFID = objFBO.id_user_page_group;
                    DataTable dt = (new RequestDAO()).SelectBy_sFID(objRequestEO.sFID);
                    if (CommonsCheck.DataTable_OK(dt))
                    {
                        List<RequestEO> lstRes = new List<RequestEO>();
                        lstRes = (List<RequestEO>)ConvertEx.ConvertDataTableToListObject<RequestEO>(dt, lstRes.GetType());
                        if (CommonsCheck.ListObject_OK(lstRes))
                        {
                            if (lstRes.Exists(n => StringEx.Equals(n.sEmail, objRequestEO.sEmail)))
                            {
                                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.INFO, "Bạn đã gửi truy vấn với facebook id này rồi, vui lòng đợi kết quả hoặc gửi yêu cầu khác.");
                                return;
                            }
                            else
                            {
                                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.INFO, "Đã có " + lstRes.Count + " người gửi truy vấn giống bạn.");
                                objRequestEO.iStatus = FacebookApp.SharedLibraries.Constants.Request_iStatus.duplicate;
                            }
                        }
                    }
                    setView(false);
                }
            }
            catch (Exception ex)
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex);
            }
        }

        protected void setView(Boolean isShowInput)
        {
            pnlCheck.Visible = isShowInput;
            pnlRegister.Visible = (!isShowInput);
            if (isShowInput)
            {
                MsgUC1.setClearMsg();
                txtsUrl.Text = "";
                txtsEmail.Text = "";
            }
        }

        protected void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                MsgUC1.setClearMsg();
                KeyValueEO _KeyValueEO = new KeyValueEO();
                _KeyValueEO = OtherEx.ConvertNumberToChar(_KeyValueEO, 4);

                objRequestEO.PK_iRID = Convert.ToInt64(_KeyValueEO.K);
                objRequestEO.sRID = _KeyValueEO.V;
                //objRequestEO.sFID = _sFID;
                //objRequestEO.sEmail = _sEmail;
                objRequestEO.iScan_Count = 0;
                //objRequestEO.iType = _iType;
                //objRequestEO.iStatus = _iStatus;
                objRequestEO.bUser = true;
                objRequestEO.bPage = true;
                objRequestEO.bPost = true;
                objRequestEO.bLike = true;
                objRequestEO.bComment = true;
                objRequestEO.bReply = true;
                objRequestEO.bEmail = true;
                objRequestEO.tReceived = (new RequestDAO()).Get_DateTime_Now();
                objRequestEO.tProcessing = DateTime.MinValue;
                objRequestEO.tSuccess = DateTime.MinValue;

                if ((new RequestDAO()).Insert_Update_Delete(objRequestEO, ConstEx.Insert_Update_Delete.Insert))
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.SUCCESS, "Đăng ký thành công");
                else
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.SUCCESS, "Đăng ký không thành công");

                setView(true);
            }
            catch (Exception ex)
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex);
            }
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            setView(true);
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            setView(true);
        }
    }
}